<?php

namespace App\Http\Controllers\Operation\Model;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\Rule;
use App\Services\ModelCategoryService;
use App\Services\ModelClassService;
use App\Services\ModelService;
use App\Services\UserGroupService;
use App\ModelClass;
use App\Model;
use App\Lib\Auth\UserProfileHelper;

class ModelController extends Controller
{
    private $modelCategoryService = null;
    private $modelClassService = null;
    private $modelService = null;
    private $userProfileHelper = null;
    private $userGroupService = null;

    public function __construct(ModelCategoryService $modelCategoryService,
        ModelClassService $modelClassService,
        ModelService $modelService,
        UserGroupService $userGroupService,
        UserProfileHelper $userProfileHelper)
    {
        $this->modelCategoryService = $modelCategoryService;
        $this->modelClassService = $modelClassService;
        $this->modelService = $modelService;
        $this->userGroupService = $userGroupService;
        $this->userProfileHelper = $userProfileHelper;
    }

    public function index()
    {
        return view('operation.model.model.model');
    }

    public function getInitCategoryTrees()
    {
        return $this->modelCategoryService->getCascadeCategories();
    }

    public function getCateClasses($categoryId)
    {
        return $this->modelClassService->getClasses([
            'categoryId' => $categoryId
        ], false);
    }

    public function query(Request $request)
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();
        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];

            $input = $request->all();
            $input['ownerId'] = $currentUserGroupId;
            return $this->modelService->getModels($input);
        } else {
            return [];
        }

    }

    public function getCategory(Request $request)
    {
        return [
            'cates' => $this->modelCategoryService->getChildCategories($request->parentId),
            'classes' => $this->modelClassService->getCategoryClass($request->parentId)
        ];
    }

    public function getModelProperties(Request $request)
    {
        return $this->modelClassService->getClassDetails($request->classId);
    }

    public function create()
    {
        return view('operation.model.model.create');
    }

    public function saveNewModel(Request $request)
    {
        $managedGroupsInfo = $this->userProfileHelper->getManagedGroups();

        if (!empty($managedGroupsInfo)) {
            $currentUserGroupId = $managedGroupsInfo['currentUserGroupId'];

            $input = $request->all();

            $this->validateWhenSaveNewModel($input);
            
            $ownerId = $currentUserGroupId;
            
            $authorId = $this->userProfileHelper->user()->id;

            $this->modelService->saveNewModel($input, $authorId, $ownerId);

            return response()->json([
                'Success' => true,
                'Message' => '成功发布模型',
            ]);
        }

        return response()->json([
            'Success' => false,
            'Message' => '上传模型失败',
        ]);
    }

    public function edit($modelId)
    {
        $model = Model::findOrFail($modelId);

        $modelClassId = $model->class_id;

        $modelCates = $model->modelCates();

        \Log::info($modelCates);

        return view('operation.model.model.create', [
            'model' => $model,
            'class_id' => $modelClassId,
            'modelCates' => collect($modelCates)->pluck('id')->toArray()
        ]);
    }

    public function indexOper()
    {
        return view('operation.model.model.manage_model');
    }

    public function queryAll(Request $request)
    {
        $input = $request->all();

        $similarGroups = $this->userGroupService->getGroups(['name' => $input['owner_name']], false);

        $input['ownerIds'] = collect($similarGroups)->pluck('id')->toArray();
        
        return $this->modelService->getModels($input);
    }

    public function manageSetting($modelId)
    {
        $model = Model::findOrFail($modelId);

        return view('operation.model.model.model_setting', [
            'model' => $model
        ]);
    }

    public function delete(Request $request)
    {
        $input = $request->all();

        $this->validateWhenDeleteModel($input);
       
        $this->modelService->delete($input['id']);

        return response()->json([
            'Success' => true,
            'Message' => '成功删除模型',
        ]);
    }

    public function doSaveMainPageModelSetting(Request $request)
    {
        $input = $request->all();
        
        $this->validateWhenSaveMainSetting($input);

        $model = Model::findOrFail($input['id']);

        $model->update([
            'id' => $input['id'],
            'is_new' => $input['is_new'],
            'is_new_order' => $input['is_new_order'],
            'is_recommand' => $input['is_recommand'],
            'is_recommand_order' => $input['is_recommand_order'],
            'is_recommand_materials' => $input['is_recommand_materials'],
            'is_recommand_materials_order' => $input['is_recommand_materials_order'],
        ]);

        return response()->json([
            'Success' => true,
            'Message' => '设置成功',
        ]);
    }

    private function validateWhenSaveMainSetting(Array $input)
    {
        return Validator::make($input, [
            'id' => 'required',
            'is_new' => 'required',
            'is_new_order' => 'required|numeric',
            'is_recommand' => 'required',
            'is_recommand_order' => 'required|numeric',
            'is_recommand_materials' => 'required',
            'is_recommand_materials_order' => 'required|numeric',
        ], [
            'id.required' => '必须传入模型ID',
            'is_new.required' => '必须设置是否新品推荐的值，只能为是或者否',
            'is_new_order.required' => '必须设置是否新品推荐的显示序号',
            'is_new_order.numeric' => '新品推荐的序号必须为数字',
            'is_recommand.required' => '必须设置是否精品推荐的值，只能为是或者否',
            'is_recommand_order.required' => '必须设置是否精品推荐的显示序号',
            'is_recommand_order.numeric' => '精品推荐的序号必须为数字',
            'is_recommand_materials.required' => '必须设置是否是首页展示的素材的值，只能为是或者否',
            'is_recommand_materials_order.required' => '必须设置是否首页展示的素材的显示序号',
            'is_recommand_materialsorder.numeric' => '首页展示的素材的序号必须为数字',
        ])->validate();
    }

    private function validateWhenSaveNewModel(Array $input)
    {
        return Validator::make($input, [
            'name' => 'required|max:125|unique:models,name',
            'class_id' => 'required|exists:model_classes,id',
            'price' => 'required|numeric',
            'main_image' => 'required|max:255',
            'fileThumbs' => 'max:1000',
            'fileThumbGuid' => 'max:100',
            'fileLines' => 'max:1000',
            'fileLineGuid' => 'max:100',
            'modelGuid' => 'required|max:100'
        ], [
            'name.required' => '模型名称不可为空',
            'name.max' => '模型名称长度不可超过:max',
            'name.unique' => '模型名称不可重复',
            'class_id.required' => '必须传入模型品类',
            'class_id.exists' => '模型品类不存在',
            'price.required' => '没有传入模型价格',
            'price.numeric' => '模型价格不是数字类型',
            'main_image.required' => '没有传入模型主图',
            'main_image.max' => '模型主图ID长度不可超过:max',
            //'fileThumbs.required' => '没有传入模型缩略图',
            'fileThumbs.max' => '模型缩略图长度不可超过:max',
            //'fileLines.required' => '没有传入模型线框图',
            'fileLines.max' => '模型线框图长度不可超过:max',
            'modelGuid.required' => '还没有上传模型',
            'modelGuid.max' => '模型GUID长度不可超过:max',
        ])->after(function ($validator) use ($input){
            if (!empty($input['fileThumbs'])) {
                $thumbs = explode(',', $input['fileThumbs']);

                if (count($thumbs) > 5) {
                    $validator->errors()->add('fileThumbs.over', '模型缩略图不可超过5张');
                }
            }
            if (!empty($input['fileLines'])) {
                $thumbs = explode(',', $input['fileLines']);

                if (count($thumbs) > 3) {
                    $validator->errors()->add('fileLines.over', '模型线框图不可超过3张');
                }
            }
        })->validate();
    }

    private function validateWhenDeleteModel($input)
    {
        return Validator::make($input, [
                'id' => 'required|exists:models,id'
            ], [
                'id.required' => '必须传入模型ID',
                'id.exists' => '该模型ID参数有误，不存在'
            ])->after(function ($validator) use($input) {
                //if ($this->modelService->hasConstrait($input['id'])) {
                //    $validator->errors()->add('id', '该模型存在其它关联，不可删除');
                //}
            })->validate();
    }
}
